import queue
from subprocess import Popen
import threading
import time

class PopenQueue(object):
    def __init__(self, p: Popen):
        self.p=p
        self.err_q=queue.Queue()
        self.out_q=queue.Queue()

    def StartReadingThread(self):
        err_th = threading.Thread(target=PopenQueue.__read_err, args=(self,))
        err_th.start()
        out_th = threading.Thread(target=PopenQueue.__read_out, args=(self,))
        out_th.start()

    def __read_err(self):
        while self.p.poll() is None:
            time.sleep(0.1)
            data = self.p.stderr.readline()
            if data:
                line=data.decode()
                self.err_q.put(line.strip())
        print('Read error thread stop.')

    def __read_out(self):
        while self.p.poll() is None:
            time.sleep(0.1)
            data = self.p.stdout.readline()
            if data:
                line=data.decode()
                #print(line)
                self.out_q.put(line.strip())
        print('Read out thread stop.')

    def err_empty(self):
        return self.err_q.empty()
    
    def out_empty(self):
        return self.out_q.empty()
    
    def err_get(self):
        return self.err_q.get()

    def out_get(self):
        return self.out_q.get()
    
    def err_clear(self):
        self.err_q.queue.clear()

    def out_clear(self):
        self.out_q.queue.clear()
    
